package com.ams.thread.lesson8;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author： 乐哥聊编程(全平台同号)
 */
@Slf4j
public class Example20 {
    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private static Lock readLock = lock.readLock();
    private static Lock writeLock = lock.writeLock();

    public static void main(String[] args) {
//        new Thread(new Thread1("读线程1")).start();
//        new Thread(new Thread1("读线程2")).start();
//        new Thread(new Thread1("读线程3")).start();
//        new Thread(new Thread1("读线程4")).start();
//        new Thread(new Thread2("写线程1")).start();
        new Thread(new Thread2("写线程2")).start();
    }


    /**
     * 读锁线程
     */
    static class Thread1 implements Runnable {
        private String name;
        public Thread1(String name) {
            this.name = name;
        }
        @Override
        public void run() {
            readLock.lock();
            int i=0;
            while (i++<10){
                log.info("线程 {} 在运行",name);
                ThreadUtil.sleep(1000);
            }
            readLock.unlock();
        }
    }
    /**
     * 写锁线程
     */
    static class Thread2 implements Runnable {
        private String name;
        public Thread2(String name) {
            this.name = name;
        }
        @Override
        public void run() {
            writeLock.lock();
            int i=0;
            while (i++<5){
                log.info("线程 {} 在运行",name);
                ThreadUtil.sleep(1000);
            }
            writeLock.unlock();
        }
    }
}
